//
//  HMNetworkTools.swift
//  03-Swift网络框架的封装
//
//  Created by itcast on 17/3/20.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

//声明枚举
enum HTTPMethod: Int {
    case GET = 0
    case POST
}

// swift 调用OC  先添加桥接文件 再在桥接文件中导入需要使用的类的头文件
//但是如果通过cocoapods管理的第三方框架 只需要导入命名空间即可
import AFNetworking

class WBNetworkTools: AFHTTPSessionManager {
    //单例对象
    static let shared: WBNetworkTools = {
        let tools = WBNetworkTools()
        
        //设置支持的解析数据的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
        //封装网络请求的核心方法
    func request(method: HTTPMethod,urlString: String, paramters: Any?, finished: @escaping (Any?, Error?) -> ()) {
        
        //定义闭包对象
        let success = { (task: URLSessionDataTask,responseObject: Any?) -> () in
            //执行成功的回调
//            print(responseObject!)
            finished(responseObject, nil)
        }
        
        let failure = { (task: URLSessionDataTask?, error :Error) -> () in
            //执行失败的回调
            print(error)
            finished(nil, error)
        }
        if method == .GET {
            //get请求
            get(urlString, parameters: paramters, progress: nil, success: success, failure: failure)
        } else {
            //post 请求
            post(urlString, parameters: paramters, progress: nil, success: success, failure: failure)
        }
    }
}


//MARK: 微博首页数据请求
extension WBNetworkTools {
    func homeLoadData(since_id: Int64, max_id: Int64,finished: @escaping (Any?, Error?) -> ()){

        // 请求URL
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = [
            "access_token": WBUserAccountViewModel.shared.accessToken!,
            "since_id": "\(since_id)",
            "max_id": "\(max_id)"
        ]

        //发送请求
        request(method: HTTPMethod.GET, urlString: urlString, paramters: params, finished: finished)
    }
}


// 发布图片微博

extension WBNetworkTools {
    
    
    
    // 发布文字微博
    func composeUpdate(status: String?, finished: @escaping (Any?, Error?) -> ()){
        // 请求URL
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let params = [
            "access_token":WBUserAccountViewModel.shared.accessToken!,
            "status": status ?? ""
        ]
        request(method: HTTPMethod.POST, urlString: urlString, paramters: params, finished: finished)
    }

    
    
    func composeUpload(status:String?,imageList:[UIImage], finished: @escaping (Any?, Error?) -> ()){
        // 请求的url
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数

        let params =  ["access_token":WBUserAccountViewModel.shared.accessToken!,
                       "status": status ?? ""
        ]
        post(urlString, parameters: params, constructingBodyWith: { (formdata) in
            
            for image in imageList {
                let data = UIImagePNGRepresentation(image)
                guard let d = data else{
                    return
                }
                formdata.appendPart(withFileData: d, name: "pic", fileName: "suobian", mimeType: "application/octet-stream")
            }
        }, progress: nil, success: { (_, response) in
            finished(response, nil)
        }, failure: { (_, error) in
            finished(nil, error)
        })
    }
    
}
